import React, { useState } from 'react';
import { 
  Flex, Radio, Card, Table, Checkbox, Space, Button, message, Tooltip, Input,
  Descriptions,  // 新增导入Descriptions组件
  Typography,
  Tag
} from 'antd';
import type { 
  CheckboxChangeEvent,
  DescriptionsProps  // 新增导入Descriptions类型
} from 'antd/es';
import { CheckOutlined, FileDoneOutlined, InfoOutlined, SearchOutlined, UsergroupAddOutlined, UserOutlined } from '@ant-design/icons';
import http from '~/api/http';
import type { Iganyuf,Iganyuaddf } from '~/types/ganyuf';
import type { IGanyux } from '~/types/ganyux';
import type { IGanyut } from '~/types/ganyut';
import dayjs from 'dayjs';
import TextArea from 'antd/es/input/TextArea';
import CheckResultPage from './CheckResultPage';

// 疾病类型定义
interface Disease {
  id: string;
  name: string;
  desc?: string; // 疾病描述，用于 tooltip
}

interface AddUserFormProps {
  onSuccess: () => void; // 原有：新增成功回调
  onCancel: () => void; // 原有：取消回调
  onGenerateReport: () => void; // 新增：生成报告回调
}

// 选择结果类型
interface DiseaseSelection {
  self: Record<string, boolean>; // 本人情况
  family: Record<string, boolean>; // 亲属情况
}

// 膳食表单数据类型
interface DietFormData {
  "1. 米、面等主食每日摄入量": number | ""; // 数字或空（未选择）
  "2. 新鲜水果每日摄入量": number | "";
  "3. 新鲜蔬菜每日摄入量": number | "";
  "11. 每日饮绿茶量": number | "";
  "12. 饮食偏好": string[]; // 多选仍为字符串数组
  "13. 饮食习惯": string[];
}

// 体力活动表单数据类型
interface ActivityFormData {
  [key: string]: string;
}

// 吸烟情况数据类型
interface SmokingData {
  question1: string;
  question2: {
    morning15: boolean;
    morningHour: boolean;
    noSmokingPlace: boolean;
  };
  question3: string;
  question4: string;
}


// 单选组件（Antd风格）
const DietRadioItem = ({ title, options, value, onChange }: {
  title: string;
  options: { value: string; label: string }[];
  value: string;
  onChange: (question: string, val: string) => void;
}) => {
  return (
    <div style={{ marginBottom: 16 }}>
      <p style={{ marginBottom: 8, fontSize: 14, fontWeight: 500 }}>{title}</p>
      <Radio.Group
        value={value}
        onChange={e => onChange(title, e.target.value)}
        size="small"
      >
        <Flex wrap="wrap" gap={12}>
          {options.map(option => (
            <Radio.Button
              key={option.value}
              value={option.value}
              size="small"
              style={{ padding: '2px 12px' }}
            >
              {option.label}
            </Radio.Button>
          ))}
        </Flex>
      </Radio.Group>
    </div>
  );
};

// 多选组件（Antd风格）
const DietCheckboxItem = ({ title, options, value, onChange }: {
  title: string;
  options: { value: string; label: string }[];
  value: string[];
  onChange: (question: string, val: string[]) => void;
}) => {
  const handleChange = (optionValue: string, checked: boolean) => {
    const newValues = checked
      ? [...value, optionValue]
      : value.filter(item => item !== optionValue);
    onChange(title, newValues);
  };

  return (
    <div style={{ marginBottom: 16 }}>
      <p style={{ marginBottom: 8, fontSize: 14, fontWeight: 500 }}>{title}</p>
      <Flex wrap="wrap" gap={16}>
        {options.map(option => (
          <Checkbox
            key={option.value}
            checked={value.includes(option.value)}
            onChange={(e: CheckboxChangeEvent) => handleChange(option.value, e.target.checked)}
            size="small"
          >
            {option.label}
          </Checkbox>
        ))}
      </Flex>
    </div>
  );
};

// 体力活动单选组件（Antd风格）
const ActivityRadioItem = ({ title, options, value, onChange }: {
  title: string;
  options: { value: string; label: string }[];
  value: string;
  onChange: (question: string, val: string) => void;
}) => {
  return (
    <div style={{ marginBottom: 16 }}>
      <p style={{ marginBottom: 8, fontSize: 14, fontWeight: 500 }}>{title}</p>
      <Radio.Group
        value={value}
        onChange={e => onChange(title, e.target.value)}
        size="small"
      >
        <Flex wrap="wrap" gap={12}>
          {options.map(option => (
            <Radio.Button
              key={option.value}
              value={option.value}
              size="small"
              style={{ padding: '2px 12px' }}
            >
              {option.label}
            </Radio.Button>
          ))}
        </Flex>
      </Radio.Group>
    </div>
  );
};

// 吸烟情况调查组件
const SmokingSurvey = ({ 
  smokingData, 
  setSmokingData 
}: { 
  smokingData: SmokingData;
  setSmokingData: (data: SmokingData) => void;
}) => {
  // 处理单选题选中状态的函数
  const handleSingleChoice = (question: string, value: string) => {
    setSmokingData(prev => ({
      ...prev,
      [question]: value
    }));
  };

  // 处理多选题选中状态的函数
  const handleMultiChoice = (key: string) => {
    setSmokingData(prev => ({
      ...prev,
      question2: {
        ...prev.question2,
        [key]: !prev.question2[key]
      }
    }));
  };

  return (
    <div className="smoking-survey" style={{ padding: '12px 8px' }}>
      <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>吸烟情况调查</h3>
      
      {/* 问题1：是否吸烟（单选题） */}
      <div className="question" style={{ margin: '15px 0' }}>
        <span style={{ display: 'inline-block', width: 180 }}>1. 您现在吸烟吗：</span>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question1"
            value="不吸烟"
            checked={smokingData.question1 === '不吸烟'}
            onChange={() => handleSingleChoice('question1', '不吸烟')}
          />
          不吸烟
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question1"
            value="戒烟大于等于7年"
            checked={smokingData.question1 === '戒烟大于等于7年'}
            onChange={() => handleSingleChoice('question1', '戒烟大于等于7年')}
          />
          戒烟大于等于7年
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question1"
            value="吸烟"
            checked={smokingData.question1 === '吸烟'}
            onChange={() => handleSingleChoice('question1', '吸烟')}
          />
          吸烟
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question1"
            value="戒烟小于7年"
            checked={smokingData.question1 === '戒烟小于7年'}
            onChange={() => handleSingleChoice('question1', '戒烟小于7年')}
          />
          戒烟小于7年
        </label>
        <label>
          <input
            type="checkbox"
            value="常被动吸烟"
            checked={smokingData.question1 === '常被动吸烟'}
            onChange={() => handleSingleChoice('question1', '常被动吸烟')}
          />
          常被动吸烟
        </label>
      </div>

      {/* 问题2：吸烟行为（多选题） */}
      <div className="question" style={{ margin: '15px 0' }}>
        <span style={{ display: 'inline-block', width: 180 }}>2. 您是否有以下情况：</span>
        <label style={{ marginRight: 15 }}>
          <input
            type="checkbox"
            checked={smokingData.question2.morning15}
            onChange={() => handleMultiChoice('morning15')}
          />
          早晨15分钟内吸第一支烟
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="checkbox"
            checked={smokingData.question2.morningHour}
            onChange={() => handleMultiChoice('morningHour')}
          />
          早晨醒来后一小时比其他时间吸更多烟
        </label>
        <label>
          <input
            type="checkbox"
            checked={smokingData.question2.noSmokingPlace}
            onChange={() => handleMultiChoice('noSmokingPlace')}
          />
          在禁烟场所或卧病时很难控制吸烟需求
        </label>
      </div>

      {/* 问题3：每天吸烟量（单选题） */}
      <div className="question" style={{ margin: '15px 0' }}>
        <span style={{ display: 'inline-block', width: 180 }}>3. 您平均每天吸多少支烟：</span>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question3"
            value="小于5支"
            checked={smokingData.question3 === '小于5支'}
            onChange={() => handleSingleChoice('question3', '小于5支')}
          />
          小于5支
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question3"
            value="5-15支"
            checked={smokingData.question3 === '5-15支'}
            onChange={() => handleSingleChoice('question3', '5-15支')}
          />
          5-15支
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question3"
            value="16-25支"
            checked={smokingData.question3 === '16-25支'}
            onChange={() => handleSingleChoice('question3', '16-25支')}
          />
          16-25支
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question3"
            value="26-40支"
            checked={smokingData.question3 === '26-40支'}
            onChange={() => handleSingleChoice('question3', '26-40支')}
          />
          26-40支
        </label>
        <label>
          <input
            type="radio"
            name="question3"
            value="大于40支"
            checked={smokingData.question3 === '大于40支'}
            onChange={() => handleSingleChoice('question3', '大于40支')}
          />
          大于40支
        </label>
      </div>

      {/* 问题4：吸烟时长（单选题） */}
      <div className="question" style={{ margin: '15px 0' }}>
        <span style={{ display: 'inline-block', width: 180 }}>4. 您吸烟有多长时间：</span>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question4"
            value="小于5年"
            checked={smokingData.question4 === '小于5年'}
            onChange={() => handleSingleChoice('question4', '小于5年')}
          />
          小于5年
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question4"
            value="5-15年"
            checked={smokingData.question4 === '5-15年'}
            onChange={() => handleSingleChoice('question4', '5-15年')}
          />
          5-15年
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question4"
            value="16-25年"
            checked={smokingData.question4 === '16-25年'}
            onChange={() => handleSingleChoice('question4', '16-25年')}
          />
          16-25年
        </label>
        <label style={{ marginRight: 15 }}>
          <input
            type="radio"
            name="question4"
            value="26-40年"
            checked={smokingData.question4 === '26-40年'}
            onChange={() => handleSingleChoice('question4', '26-40年')}
          />
          26-40年
        </label>
        <label>
          <input
            type="radio"
            name="question4"
            value="大于40年"
            checked={smokingData.question4 === '大于40年'}
            onChange={() => handleSingleChoice('question4', '大于40年')}
          />
          大于40年
        </label>
      </div>
    </div>
  );
};

const AddUserForm: React.FC<AddUserFormProps> = ({ 
  onSuccess, 
  onCancel, 
  onGenerateReport 
}) => {
  const [parentValue, setParentValue] = useState('a');
  const [childValue, setChildValue] = useState('');
  
  // 疾病相关状态
  const diseases: Disease[] = [
    { id: 'diabetes', name: '糖尿病', desc: '以高血糖为特征的代谢性疾病' },
    { id: 'hypertension', name: '高血压', desc: '动脉血压持续升高的慢性疾病' },
    { id: 'obesity', name: '肥胖症', desc: '体内脂肪堆积过多的状态' },
    { id: 'chd', name: '冠心病', desc: '冠状动脉粥样硬化性心脏病' },
    { id: 'fattyLiver', name: '脂肪肝', desc: '肝细胞内脂肪堆积过多' },
    { id: 'gout', name: '痛风', desc: '嘌呤代谢紊乱导致的关节疾病' },
    { id: 'migraine', name: '偏头痛', desc: '反复发作的神经血管性头痛' },
    { id: 'stroke', name: '中风', desc: '脑血管突然破裂或阻塞引起的疾病' },
    { id: 'copd', name: '慢阻肺', desc: '阻塞性肺疾病的简称' },
    { id: 'depression', name: '抑郁症', desc: '以显著心境低落为主要特征' },
    { id: 'stomachCancer', name: '胃癌', desc: '发生于胃部的恶性肿瘤' },
    { id: 'colorectalCancer', name: '肠癌', desc: '结肠或直肠的恶性肿瘤' },
    { id: 'lungCancer', name: '肺癌', desc: '起源于肺部的恶性肿瘤' },
    { id: 'cervicalCancer', name: '宫颈癌', desc: '发生在子宫颈的恶性肿瘤' },
  ];

  const initialDiseaseSelection: DiseaseSelection = {
    self: diseases.reduce((acc, disease) => ({ ...acc, [disease.id]: false }), {}),
    family: diseases.reduce((acc, disease) => ({ ...acc, [disease.id]: false }), {}),
  };
  const [diseaseSelection, setDiseaseSelection] = useState<DiseaseSelection>(initialDiseaseSelection);

  // 膳食摄入相关状态
  const [dietFormData, setDietFormData] = useState<DietFormData>({
    "1. 米、面等主食每日摄入量": "",
    "2. 新鲜水果每日摄入量": "",
    "3. 新鲜蔬菜每日摄入量": "",

    "11. 每日饮绿茶量": "",
    "12. 饮食偏好": [],
    "13. 饮食习惯": []
  });

  // 体力活动相关状态
  const [activityFormData, setActivityFormData] = useState<ActivityFormData>({
    "1. 您主要的工作方式是": "",
    "2. 您日常的出行方式是": "",
    "3. 您平均每周运动锻炼时间是": "",
    "4. 您一般锻炼的强度是": ""
  });

  // 吸烟情况相关状态
  const [smokingData, setSmokingData] = useState<SmokingData>({
    question1: '不吸烟',
    question2: {
      morning15: false,
      morningHour: false,
      noSmokingPlace: false
    },
    question3: '小于5支',
    question4: '小于5年'
  });

  // 风险测评用户信息数据
  const [userInfoItems, setUserInfoItems] = useState<DescriptionsProps['items']>([
    { key: '1', label: 'UserName', children: 'Zhou Maomao' },
    { key: '2', label: 'Telephone', children: '1810000000' },
    { key: '3', label: 'Live', children: 'Hangzhou, Zhejiang' },
    { key: '4', label: 'Address', span: 2, children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China' },
    { key: '5', label: 'Remark', children: 'empty' },
  ]);

  // 体力活动问题配置
  const activityQuestions = [
    {
      title: "1. 您主要的工作方式是",
      options: [
        { value: "mental", label: "脑力：从事脑力劳动者，如教育、财贸、操作电脑等" },
        { value: "light", label: "轻体力：久坐不动者，如文员、司机、缝纫、售货员等" },
        { value: "medium", label: "中体力：如装修工、瓦工、保洁等" },
        { value: "heavy", label: "重体力：如搬运重物、人力挖掘和装卸等" }
      ],
    },
    {
      title: "2. 您日常的出行方式是",
      options: [
        { value: "rare", label: "很少出行" },
        { value: "bike", label: "自行车" },
        { value: "walk", label: "步行" },
        { value: "car", label: "乘车或开车" },
        { value: "public", label: "公交或摩托" }
      ],
    },
    {
      title: "3. 您平均每周运动锻炼时间是",
      options: [
        { value: "none", label: "不锻炼" },
        { value: "less1", label: "小于1小时" },
        { value: "1-3", label: "1-3小时" },
        { value: "4-5", label: "4-5小时" },
        { value: "more5", label: "大于5小时" }
      ],
    },
    {
      title: "4. 您一般锻炼的强度是",
      options: [
        { value: "none", label: "不锻炼" },
        { value: "veryLight", label: "极轻度运动" },
        { value: "light", label: "轻度运动" },
        { value: "medium", label: "中度运动" },
        { value: "heavy", label: "重度运动" }
      ],
    },
  ];

  const activityScoreMap = {
  "1. 您主要的工作方式是": {
    "mental": 2,       // 脑力
    "light": 1,        // 轻体力
    "medium": 3,       // 中体力
    "heavy": 4         // 重体力
  },
  "2. 您日常的出行方式是": {
    "rare": 1,         // 很少出行
    "car": 3,          // 乘车或开车
    "public": 3,       // 公交或摩托
    "bike": 2,         // 自行车
    "walk": 1          // 步行
  },
  "3. 您平均每周运动锻炼时间是": {
    "none": 1,         // 不锻炼
    "less1": 2,        // 小于1小时
    "1-3": 3,          // 1-3小时
    "4-5": 4,          // 4-5小时
    "more5":5        // 大于5小时
  },
  "4. 您一般锻炼的强度是": {
    "none": 1,         // 不锻炼
    "veryLight": 2,    // 极轻度运动
    "light": 3,        // 轻度运动
    "medium": 4,       // 中度运动
    "heavy":5        // 重度运动
  }
};
const dian1=async ()=>{
console.log("ww")
ganyuf1.benb=benby
ganyuf1.qinb=qinby
ganyuf1.yins=yins1
ganyuf1.ypianh=yinp1
ganyuf1.yxig=yinxi
ganyuf1.xiyan=xiyan1
ganyuf1.tili=tili1
ganyuf1.bid=bid
console.log(ganyuf1)

  try {
    const bb = await http.post<IGanyufadd>('Ganyuf', ganyuf1);
    // 请求成功后的逻辑（如提示成功、刷新数据）
    console.log('添加成功', bb);
     message.success('添加成功')
  } catch (error) {
    // 处理错误（如提示用户、打印错误日志）
    console.error('请求失败', error);
    // 可选：抛出错误让上层处理
    // throw error;
  }
}
  // 父级与子集选项映射 - 包含风险测评子选项
  const childOptions = {
    a: [
      { value: 'a1', label: '患者病情' },
      { value: 'a2', label: '膳食摄入' },
      { value: 'a3', label: '体力活动' },
      { value: 'a4', label: '吸烟习惯' },
      { value: 'a5', label:<button  onClick={dian1}>添加</button>},
    ],
    b: [
      { value: 'b1', label: '常规检查' },
      { value: 'b2', label: '生化指标' },
      { value: 'b3', label: '影像检查' },
      { value: 'b4', label: '专科检查' },
    ],
    c: [  // 风险测评子选项
      { value: 'c1', label: '健康风险信息' },  // 对应Descriptions组件
      { value: 'c2', label: '健康风险评估' },
    
    ]
  };

  // 膳食摄入问题配置
 const dietIntakeQuestions = [
  {
    title: "1. 米、面等主食每日摄入量",
    options: [
      { value: 1, label: "<1小碗" },
      { value: 2, label: "1-2小碗" },
      { value: 3, label: "3-4小碗" },
      { value: 4, label: "5-6小碗" },
      { value: 5, label: ">6小碗" },
    ],
  },
  {
    title: "2. 新鲜水果每日摄入量",
    options: [
      { value: 1, label: "<1两" },
      { value: 2, label: "1-4两" },
      { value: 3, label: "5-8两" },
      { value: 4, label: "9-12两" },
      { value: 5, label: ">12两" },
    ],
  },
  {
    title: "3. 新鲜蔬菜每日摄入量",
    options: [
      { value: 1, label: "<2两" },
      { value: 2, label: "2-6两" },
      { value: 3, label: "7-10两" },
      { value: 4, label: "11-15两" }, // 修复：value:4 → value: 4（加空格）
      { value: 5, label: ">15两" },
    ],
  },
  {
    title: "11. 每日饮绿茶量",
    options: [
      { value: 1, label: "<3杯" }, // 修复：value:1 → value: 1（加空格）
      { value: 2, label: "3-6杯" }, // 修复：value:2 → value: 2（加空格）
      { value: 3, label: "7-9杯" }, // 修复：value:3 → value: 3（加空格）
      { value: 4, label: "10-12杯" }, // 修复：value:4 → value: 4（加空格）
      { value: 5, label: ">12杯" }, // 修复：value:5 → value: 5（加空格）
    ],
  },
];

  const dietHabitQuestions = [
    {
      title: "12. 饮食偏好",
      options: [
        { value: "甜食", label: "甜食" },
        { value: "辛辣", label: "辛辣" },
        { value: "烫食", label: "烫食" },
        { value: "咸食", label: "咸食" },
        { value: "腌制", label: "腌制" },
        { value: "硬食", label: "硬食" },
        { value: "油腻", label: "油腻" },
        { value: "煎炸", label: "煎炸" },
        { value: "烟熏", label: "烟熏" },
        { value: "高脂", label: "高脂" },
        { value: "动物内脏", label: "动物内脏" },
      ],
    },
    {
      title: "13. 饮食习惯",
      options: [
        { value: "常吃宵夜", label: "常吃宵夜" },
        { value: "不吃早餐", label: "不吃早餐" },
        { value: "暴饮暴食", label: "暴饮暴食" },
        { value: "吃饭快", label: "吃饭快" },
        { value: "饭后立即运动", label: "饭后立即运动" },
      ],
    },
  ];

  // 处理疾病复选框变化
  const handleDiseaseChange = (
    type: 'self' | 'family',
    diseaseId: string,
    checked: boolean
  ) => {
    setDiseaseSelection(prev => ({
      ...prev,
      [type]: {
        ...prev[type],
        [diseaseId]: checked,
      },
    }));
  };

  // 处理膳食表单变化
  const handleDietFormChange = (question: string, value: string | string[]) => {
    setDietFormData(prev => ({
      ...prev,
      [question]: value
    }));
  };

  // 处理体力活动表单变化
  const handleActivityFormChange = (question: string, value: string) => {
    setActivityFormData(prev => ({
      ...prev,
      [question]: value
    }));
  };

  // 提交疾病信息
const handleDiseaseSubmit = () => {
  message.success('患者病情信息提交成功！');
  
  // 获取选中的本人疾病名称并拼接成字符串
  const selectedSelfStr = diseases
    .filter(disease => diseaseSelection.self[disease.id])
    .map(disease => disease.name)
    .join('、'); // 用顿号分隔多个疾病
  
  // 获取选中的亲属疾病名称并拼接成字符串
  const selectedFamilyStr = diseases
    .filter(disease => diseaseSelection.family[disease.id])
    .map(disease => disease.name)
    .join('、');
  
  // 合并本人和亲属的疾病字符串（带标识）
  const combinedStr = `本人: ${selectedSelfStr || '无'}；亲属: ${selectedFamilyStr || '无'}`;
  benbyvalue(selectedSelfStr)
  qinbyvalue(selectedFamilyStr)
  // 控制台打印结果
  console.log('本人选中的疾病:', selectedSelfStr);
  console.log('亲属选中的疾病:', selectedFamilyStr);
  console.log('合并疾病信息:', combinedStr);
};
const [benby,benbyvalue]=useState('')
const [qinby,qinbyvalue]=useState('')
const [yins1,yinsvalue]=useState('')
const [bid1,bidvalue]=useState('')
const [yinp1,yinp1value]=useState('')
const [yinxi,yinxivalue]=useState('')
const [tili1,tilivalue]=useState('')
const [xiyan1,xiyanvalue]=useState(0)
  // 提交膳食信息
  // 提交膳食信息（修改后，新增饮食偏好和习惯的处理）
const handleDietSubmit = () => {
  // 1. 筛选所有“膳食摄入情况”题目（1.、2.、3.、11.开头）
  const requiredFields = Object.keys(dietFormData).filter(key => 
    /^(1\.|2\.|3\.|11\.)/.test(key) 
  );

  // 2. 验证：确保所有题目都已选择（值不为空）
  const isComplete = requiredFields.every(field => 
    dietFormData[field] !== "" && dietFormData[field] !== undefined
  );

  if (!isComplete) {
    message.warning('请完成所有膳食摄入情况的填写');
    return;
  }

  // 3. 累加：所有题目值求和
  let dietTotalValue = 0;
  requiredFields.forEach(field => {
    const selectedValue = dietFormData[field] as number;
    dietTotalValue += selectedValue;
  });

  // 4. 新增：处理饮食偏好和饮食习惯（数组转字符串）
  const dietPreference = (dietFormData["12. 饮食偏好"] as string[]).join('、') || '无'; // 数组转字符串，默认“无”
  const eatingHabit = (dietFormData["13. 饮食习惯"] as string[]).join('、') || '无';

  // 5. 提示与打印（包含所有信息）
  message.success(`膳食摄入信息提交成功！4道题目值总和：${dietTotalValue}`);
  if(dietTotalValue<8){
    yinsvalue('摄入过少')
  }else if(dietTotalValue>=8&&dietTotalValue<16){
  yinsvalue('正常')
  }else{
     yinsvalue('摄入过多')
  }
  yinp1value(dietPreference)
  yinxivalue(eatingHabit)
  console.log('===== 膳食信息汇总 =====');
  console.log('膳食摄入情况题目总和：', dietTotalValue);
  console.log('饮食偏好：', dietPreference); // 打印字符串形式
  console.log('饮食习惯：', eatingHabit); // 打印字符串形式
  console.log('各题原始值：', requiredFields.map(field => ({ [field]: dietFormData[field] })));
};

  // 提交体力活动信息
const handleActivitySubmit = () => {
  // 1. 验证必填项（所有题目都需选择）
  const isComplete = Object.values(activityFormData).every(value => value !== '');
  if (!isComplete) {
    message.warning('请完成所有体力活动情况的填写');
    return;
  }

  // 2. 计算体力活动总分和各题分数明细
  let activityTotalScore = 0; // 总分
  const activityScoreDetail: Record<string, number> = {}; // 明细

  Object.entries(activityFormData).forEach(([question, selectedValue]) => {
    // 从映射表中获取当前选项的分数
    const questionScoreMap = activityScoreMap[question as keyof typeof activityScoreMap];
    const score = questionScoreMap[selectedValue as keyof typeof questionScoreMap];
    
    activityScoreDetail[question] = score; // 记录明细
    activityTotalScore += score; // 累加总分
  });
if(activityTotalScore<=8){
  tilivalue('缺乏锻炼')
}else if(activityTotalScore>8&&activityTotalScore<14){
 tilivalue('正常')
}else{
  tilivalue('体力活动过度')
}
  // 3. 提示与打印结果
  message.success(`体力活动信息提交成功！总分：${activityTotalScore}分`);
  console.log('===== 体力活动分数汇总 =====');
  console.log('各题分数明细：', activityScoreDetail);
  console.log('体力活动总分：', activityTotalScore);
  console.log('原始选择数据：', activityFormData);
};

  // 提交吸烟情况信息
  const handleSmokingSubmit = () => {
    message.success('吸烟习惯信息提交成功！');
    console.log('吸烟情况数据：', smokingData);
    if(smokingData.question1=="不吸烟"){
      xiyanvalue(0)
    }else{
       xiyanvalue(1)
    }
  };

  // 重置疾病信息
  const handleDiseaseReset = () => {
    setDiseaseSelection(initialDiseaseSelection);
  };

  // 重置膳食信息
  const handleDietReset = () => {
    setDietFormData({
      "1. 米、面等主食每日摄入量": "",
      "2. 新鲜水果每日摄入量": "",
      "3. 新鲜蔬菜每日摄入量": "",
    
      "11. 每日饮绿茶量": "",
      "12. 饮食偏好": [],
      "13. 饮食习惯": []
    });
  };

  // 重置体力活动信息
  const handleActivityReset = () => {
    setActivityFormData({
      "1. 您主要的工作方式是": "",
      "2. 您日常的出行方式是": "",
      "3. 您平均每周运动锻炼时间是": "",
      "4. 您一般锻炼的强度是": ""
    });
  };

  // 重置吸烟情况信息
  const handleSmokingReset = () => {
    setSmokingData({
      question1: '不吸烟',
      question2: {
        morning15: false,
        morningHour: false,
        noSmokingPlace: false
      },
      question3: '小于5支',
      question4: '小于5年'
    });
  };

  // 构建疾病表格列
  const diseaseColumns = [
    {
      title: '疾病情况',
      dataIndex: 'category',
      key: 'category',
      width: 90,
      fixed: 'left',
      render: (text: string) => <span style={{ fontWeight: 600, fontSize: 13 }}>{text}</span>,
    },
    ...diseases.map(disease => ({
      title: (
        <Tooltip title={disease.desc || disease.name}>
          <span style={{ fontSize: 12, display: 'flex', alignItems: 'center' }}>
            {disease.name}
            {disease.desc && <InfoOutlined style={{ fontSize: 10, marginLeft: 3, opacity: 0.7 }} />}
          </span>
        </Tooltip>
      ),
      dataIndex: disease.id,
      key: disease.id,
      width: 65,
      render: (_: any, record: { type: 'self' | 'family' }) => (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Checkbox
            checked={diseaseSelection[record.type][disease.id]}
            onChange={(e: CheckboxChangeEvent) =>
              handleDiseaseChange(record.type, disease.id, e.target.checked)
            }
            size="small"
          />
        </div>
      ),
    })),
  ];

  // 疾病表格数据
  const diseaseTableData = [
    { key: 'self', category: '1.本人', type: 'self' },
    { key: 'family', category: '2.亲属', type: 'family' },
  ];

  // 渲染膳食摄入表单
  const renderDietContent = () => (
    <div style={{ marginTop: 12 }}>
      <div style={{ marginBottom: 16 }}>
        <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
          一、膳食摄入情况
        </h3>
        <div style={{ paddingLeft: 8 }}>
          {dietIntakeQuestions.map((question, index) => (
            <DietRadioItem
              key={index}
              title={question.title}
              options={question.options}
              value={dietFormData[question.title] as string}
              onChange={handleDietFormChange}
            />
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
          二、饮食习惯
        </h3>
        <div style={{ paddingLeft: 8 }}>
          {dietHabitQuestions.map((question, index) => (
            <DietCheckboxItem
              key={index}
              title={question.title}
              options={question.options}
              value={dietFormData[question.title] as string[]}
              onChange={handleDietFormChange}
            />
          ))}
        </div>
      </div>

      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button
          onClick={handleDietReset}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          重置
        </Button>
        <Button
          type="primary"
          onClick={handleDietSubmit}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          提交膳食信息
        </Button>
      </Space>
    </div>
  );

  // 渲染体力活动表单
  const renderActivityContent = () => (
    <div style={{ marginTop: 12 }}>
      <div style={{ marginBottom: 16 }}>
        <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
          体力活动情况调查
        </h3>
        <div style={{ paddingLeft: 8 }}>
          {activityQuestions.map((question, index) => (
            <ActivityRadioItem
              key={index}
              title={question.title}
              options={question.options}
              value={activityFormData[question.title]}
              onChange={handleActivityFormChange}
            />
          ))}
        </div>
      </div>

      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button
          onClick={handleActivityReset}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          重置
        </Button>
        <Button
          type="primary"
          onClick={handleActivitySubmit}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          提交体力活动信息
        </Button>
      </Space>
    </div>
  );

  // 渲染吸烟习惯表单
  const renderSmokingContent = () => (
    <div style={{ marginTop: 12 }}>
      <SmokingSurvey 
        smokingData={smokingData} 
        setSmokingData={setSmokingData} 
      />
      
      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
        <Button
          onClick={handleSmokingReset}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          重置
        </Button>
        <Button
          type="primary"
          onClick={handleSmokingSubmit}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          提交吸烟习惯信息
        </Button>
      </Space>
    </div>
  );

   const [ganyutData, setGanyutData] = useState<IGanyut[]>([]); // fetchUsers1 数据
  const [ganyuxData, setGanyuxData] = useState<IGanyux[]>([]); // fetchUsers2 数据
  const [ganyufData, setGanyufData] = useState<Iganyuf[]>([]); // fetchUsers3 数据
const { Text } = Typography;


const STATUS_CONFIG = [
  { value: 0, label: '正常', color: 'success', bgColor: '#f6ffed', borderColor: '#52c41a', gradient: 'linear-gradient(90deg, #f6ffed 0%, #eaffea 100%)' },
  { value: 1, label: '轻度', color: 'processing', bgColor: '#e6f7ff', borderColor: '#1890ff', gradient: 'linear-gradient(90deg, #e6f7ff 0%, #d1eaff 100%)' },
  { value: 2, label: '中度', color: 'warning', bgColor: '#fffbe6', borderColor: '#faad14', gradient: 'linear-gradient(90deg, #fffbe6 0%, #fff7cc 100%)' },
  { value: 3, label: '偏重', color: 'error', bgColor: '#fff2e8', borderColor: '#ff7a45', gradient: 'linear-gradient(90deg, #fff2e8 0%, #ffe8d6 100%)' },
  { value: 4, label: '严重', color: 'error', bgColor: '#fff1f0', borderColor: '#f5222d', gradient: 'linear-gradient(90deg, #fff1f0 0%, #ffeeee 100%)' },
];
const PSYCHOLOGY_FIELDS = {
  xin: '躯体化',
  xin1: '强迫症化',
  xin2: '人际关系敏感',
  xin3: '抑郁', // 注：你写的“犹豫”推测是“抑郁”，若需调整直接改这里
  xin4: '焦虑',
  xin5: '敌对',
  xin6: '恐怖',
  xin7: '偏执',
  xin8: '精神病性'
};
// 2. Ganyux核心字段（剔除姓名、性别、ID，只保留档案号、记录时间等必要信息）
const GANYUX_CORE_FIELDS = ['fileNumber', 'xdata']; // 仅保留：档案编号、记录时间（xdata为时间字段）

// 3. 时间格式化工具函数（与参考页面一致）
const formatDate = (dateStr: string | number | undefined): string => {
  if (!dateStr) return '未知时间';
  const timestamp = typeof dateStr === 'number' ? dateStr : new Date(dateStr).getTime();
  if (isNaN(timestamp)) return '无效时间';
  
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

const processGanyuxData = (ganyuxData: IGanyux[]) => {
  if (ganyuxData.length === 0) return { statusGroups: {} };

  const data = ganyuxData[0];
  const statusGroups: Record<number, string[]> = {}; // 状态分组：key=状态值，value=心理维度名称数组
  const targetStatus = [2, 3, 4]; // 只保留中度(2)/偏重(3)/严重(4)
  
  // 初始化分组数组
  targetStatus.forEach(status => statusGroups[status] = []);

  // 处理心理维度字段，按状态分组
  Object.entries(data).forEach(([key, val]) => {
    if (
      Object.keys(PSYCHOLOGY_FIELDS).includes(key) && // 只处理心理维度字段
      typeof val === 'number' && 
      targetStatus.includes(Number(val))
    ) {
      const statusValue = Number(val);
      // 只添加心理维度名称（如“躯体化”），不包含状态值
      statusGroups[statusValue].push(
        PSYCHOLOGY_FIELDS[key as keyof typeof PSYCHOLOGY_FIELDS]
      );
    }
  });

  // 过滤空分组（没有数据的状态不展示）
  Object.keys(statusGroups).forEach(status => {
    if (statusGroups[Number(status)].length === 0) {
      delete statusGroups[Number(status)];
    }
  });

  return { statusGroups };
};

// 所有体质字段映射（和参考页面完全一致：字段名→显示标签）
const constitutionFields: Record<string, string> = {
  qi: '气虚质',
  yan: '痰湿质',
  yin: '阴虚质',
  te: '特禀质',
  yang: '阳虚质',
  xue: '血瘀质',
  shi: '湿热质',
  yu: '气郁质',
  pin: '平和质'
};

const getClassifiedConstitutions = (ganyutData: IGanyut) => {
  const yesList: string[] = []; // 值为1 → 符合体质
  const noList: string[] = [];  // 值非1 → 不符体质

  // 遍历所有体质字段，按值分组
  Object.entries(constitutionFields).forEach(([field, label]) => {
    const fieldValue = ganyutData[field as keyof IGanyut]; // 获取字段值
    if (fieldValue === 1) {
      yesList.push(label);
    } else {
      noList.push(label);
    }
  });

  return { yesList, noList };
};
  const fetchUsers1 = async () => {
  try {
    const response = await http.getList<IGanyut>('Ganyut/chay', {});
    const filteredData = response.data.filter(n => n.bid === bid); // 按bid过滤
    setGanyutData(filteredData); // 存入状态
    console.log("Ganyut数据:", filteredData);
  } catch (error) {
    console.error("获取Ganyut数据失败:", error);
    message.error("获取Ganyut数据失败");
  }
};

// 修改 fetchUsers2：存储Iganyux数据
const fetchUsers2 = async () => {
  try {
    const response = await http.getList<IGanyux>('Ganyux/chay', {});
    const filteredData = response.data.filter(n => n.bid === bid); // 按bid过滤
    setGanyuxData(filteredData); // 存入状态
    console.log("Ganyux数据:", filteredData);
  } catch (error) {
    console.error("获取Ganyux数据失败:", error);
    message.error("获取Ganyux数据失败");
  }
};

// 修改 fetchUsers3：存储Iganyuf数据
const fetchUsers3 = async () => {
  try {
    const response = await http.getList<Iganyuf>('Ganyuf/chay', {});
    const filteredData = response.data.filter(n => n.bid === bid);
     // 按bid过滤
     setid(filteredData[0].id);
    setGanyufData(filteredData); // 存入状态
    console.log("Ganyuf数据:", filteredData);
  } catch (error) {
    console.error("获取Ganyuf数据失败:", error);
    message.error("获取Ganyuf数据失败");
  }
};
   const shua=()=>{
    message.success('信息已刷新')
    fetchUsers1()
    fetchUsers2()
    fetchUsers3()
    console.log('z')
    
   }

  // 渲染风险测评-用户基础信息（Descriptions组件）
const renderUserInfo = () => {
  // 1. 恢复 Ganyut 体测数据的完整渲染（基础信息+体质分类）
  const formatGanyutItems = (ganyutData: IGanyut[]) => {
    if (ganyutData.length === 0) {
      return [{ key: 'ganyut-empty', label: '体测数据', children: '暂无体测信息' }];
    }
    const currentData = ganyutData[0];
    const { yesList, noList } = getClassifiedConstitutions(currentData);

    return [
     
      // 体质分类（符合/不符）
      {
        key: 'g7',
        label: (
          <Text strong style={{ color: '#c41a4dff' }}>
            符合体质 <CheckOutlined />
          </Text>
        ),
        children: yesList.length > 0 ? (
          yesList.map((label, idx) => (
            <Tag key={idx} icon={<CheckOutlined />} color="error" style={{ margin: '0 4px 4px 0' }}>
              {label}
            </Tag>
          ))
        ) : (
          <Text type="secondary">无</Text>
        ),
      },
      {
        key: 'g8',
        label: (
          <Text strong style={{ color: '#4dffa6ff' }}>
            不符体质 <FileDoneOutlined />
          </Text>
        ),
        children: noList.length > 0 ? (
          noList.map((label, idx) => (
            <Tag key={idx} icon={<FileDoneOutlined />} color="success" style={{ margin: '0 4px 4px 0' }}>
              {label}
            </Tag>
          ))
        ) : (
          <Text type="secondary">无</Text>
        ),
      },
    ];
  };

  // 2. 恢复 Ganyuf 数据的完整渲染（原有逻辑不变）
const formatGanyufItems = (ganyufData: Iganyuf[]) => {
  if (ganyufData.length === 0) {
    return (
      <div style={{ 
        padding: '12px', 
        textAlign: 'center', 
        backgroundColor: '#fafafa', 
        borderRadius: 6,
        color: '#999',
        fontSize: 12
      }}>
        <InfoOutlined style={{ fontSize: 16, marginBottom: 4 }} />
        <p>暂无健康信息数据</p>
      </div>
    );
  }

  const currentData = ganyufData[0];
  // 核心健康字段（保留原筛选逻辑）
  const healthFields = [
    { key: 'benb', label: '本人疾病', icon: <UserOutlined />, color: 'red' },
    { key: 'qinb', label: '亲属疾病', icon: <UsergroupAddOutlined />, color: 'orange' },
    { key: 'yins', label: '饮食评估', icon: <FileDoneOutlined />, color: 'green' }, // 缩短标签名
    { key: 'ypianh', label: '饮食偏好', icon: <FileDoneOutlined />, color: 'blue' },
    { key: 'yxig', label: '饮食习惯', icon: <FileDoneOutlined />, color: 'purple' },
    { key: 'tili', label: '体力评估', icon: <CheckOutlined />, color: 'cyan' }, // 缩短标签名
    { key: 'xiyan', label: '吸烟状态', icon: <CheckOutlined />, color: 'magenta' },
  ];

  // 吸烟状态格式化（保持逻辑，缩小标签尺寸）
  const formatSmokingStatus = (value: number) => {
    return value === 0 
      ? <Tag color="success" size="small">不吸烟</Tag> 
      : <Tag color="error" size="small">吸烟严重</Tag>;
  };

  return (
    // 缩小网格间距，减少卡片宽度
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
      {healthFields.map((field) => {
        const value = currentData[field.key as keyof Iganyuf];
        const displayValue = value === '' || value === undefined 
          ? <span style={{ color: '#999', fontSize: 12 }}>无</span>
          : field.key === 'xiyan' ? formatSmokingStatus(Number(value)) : <span style={{ fontSize: 12 }}>{value}</span>;

        return (
          <Card
            key={field.key}
            bordered
            size="small" // 蚂蚁卡片紧凑尺寸
            style={{ 
              borderRadius: 4, 
              transition: 'all 0.3s',
              borderLeft: `2px solid ${field.color}`, // 减窄左侧色条
              boxShadow: '0 1px 4px rgba(0,0,0,0.04)' // 弱化阴影
            }}
            hoverable
            bodyStyle={{ padding: '10px' }} // 大幅减少内边距
          >
            {/* 标题区：缩小图标和文字，减少间距 */}
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 4, gap: 4 }}>
              <span style={{ color: field.color, fontSize: 14 }}>{field.icon}</span>
              <h4 style={{ margin: 0, fontSize: 13, fontWeight: 500 }}>{field.label}</h4>
            </div>
            {/* 内容区：缩小字体 */}
            <div style={{ color: '#333' }}>{displayValue}</div>
          </Card>
        );
      })}
    </div>
  );
};

  // 3. Ganyux 心理维度数据（合并相同状态，无重复标签/分数）
  const { statusGroups: ganyuxStatusGroups } = processGanyuxData(ganyuxData);
  const sortedStatus = Object.keys(ganyuxStatusGroups)
    .map(Number)
    .sort((a, b) => a - b); // 按状态严重程度排序（中度→偏重→严重）

  return (
    <div style={{ marginTop: 12 }}>
      <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
        健康风险信息详情
      </h3>

      {/* 1. 体测信息（Ganyut 数据）- 完全恢复 */}
      <Descriptions
        title="体测详情"
        layout="vertical"
        items={formatGanyutItems(ganyutData)}
        bordered
        size="small"
        style={{ marginBottom: 16 }}
       
      />

      {/* 2. 心理维度信息（Ganyux 数据）- 优化展示 */}
      <div style={{ marginBottom: 16 }}>
        <Typography.Title level={4} style={{ 
          margin: '0 0 16px 0', 
          paddingBottom: '8px', 
          borderBottom: '1px solid #f0f0f0',
          color: '#1890ff',
          fontSize: 16
        }}>
          心理维度异常状态
        </Typography.Title>

        <Space direction="vertical" size="12px" style={{ width: '100%' }}>
          {sortedStatus.length > 0 ? (
            sortedStatus.map(status => {
              const config = STATUS_CONFIG.find(c => c.value === status)!;
              const psychologyItems = ganyuxStatusGroups[status];

              return (
                <Card
                  key={status}
                  title={<Tag color={config.color} size="small">{config.label}</Tag>}
                  bordered={false}
                  style={{ 
                    boxShadow: '0 1px 2px rgba(0,0,0,0.04)', 
                    borderRadius: 6,
                    borderLeft: `3px solid ${config.borderColor}`,
                    background: config.gradient
                  }}
                  bodyStyle={{ 
                    padding: '12px 16px', 
                    marginTop: 0,
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: 12
                  }}
                  titleStyle={{ padding: '8px 16px', fontSize: 13, fontWeight: 500 }}
                >
                  {psychologyItems.map((item, idx) => (
                    <Tag key={idx} color="default" style={{ fontSize: 12, backgroundColor: '#f5f5f5' }}>
                      {item}
                    </Tag>
                  ))}
                </Card>
              );
            })
          ) : (
            <Typography.Text type="secondary" style={{ fontSize: 13, padding: '16px 0', display: 'block' }}>
              暂无躯体化、强迫症化等心理维度的中度及以上异常状态
            </Typography.Text>
          )}
        </Space>
      </div>

      {/* 3. Ganyuf 数据 - 完全恢复 */}
<div style={{ marginBottom: 12 }}>
  <Typography.Title level={4} style={{ 
    margin: '0 0 10px 0', // 减少标题上下间距
    paddingBottom: '4px', // 减窄标题下划线
    borderBottom: '1px solid #f0f0f0',
    color: '#1890ff',
    fontSize: 14 // 缩小标题字体
  }}>
    健康信息汇总
  </Typography.Title>
  {formatGanyufItems(ganyufData)}
  {/* 缩小按钮尺寸和间距 */}
  {/* <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
    <Button size="small" style={{ padding: '2px 8px' }}>编辑</Button>
  </div> */}
</div>

      {/* 刷新按钮 */}
      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button onClick={shua} size="small">刷新数据</Button>
      </Space>
    </div>
  );
};
const [value1,setvalue]=useState('')
const changeCount2 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setvalue(event.target.value);
  };
const jiay= async()=>{
  
  dd.id=idy;
  dd.pinj=value1
  console.log(dd)
     try {
    const bb = await http.put<IGanyufadd>('Ganyuf', dd);
    // 请求成功后的逻辑（如提示成功、刷新数据）
    console.log('修改成功', bb);
    onGenerateReport()
  } catch (error) {
    // 处理错误（如提示用户、打印错误日志）
    console.error('请求失败', error);
    // 可选：抛出错误让上层处理
    // throw error;
  } 

}
  // 渲染风险测评-健康风险评估
  const renderRiskAssessment = () => (
    <div style={{ marginTop: 12 }}>
      <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
        健康风险评估结果
      </h3>
      <div style={{ padding: 16, backgroundColor: '#f5f7fa', borderRadius: 4, marginBottom: 16 }}>
        
        <div>
          <span style={{ fontWeight: 500, display: 'block', marginBottom: 8 }}>风险因素分析：</span>
          <ul style={{ margin: 0, paddingLeft: 20 }}>
           <TextArea value={value1} onChange={changeCount2} rows={4} placeholder="填写报告" maxLength={200} />
          </ul>
        </div>
      </div>
      
      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button
          onClick={() => message.info('评估已重新计算')}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          重新评估
        </Button>
        <Button
          type="primary"
          onClick={jiay}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          生成报告
        </Button>
      </Space>
    </div>
  );

  // 渲染风险测评-干预建议
  const renderIntervention = () => (
    <div style={{ marginTop: 12 }}>
      <h3 style={{ fontSize: 15, margin: '12px 0', color: '#1890ff' }}>
        健康干预建议
      </h3>
      <div style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ marginBottom: 16 }}>
          <h4 style={{ fontSize: 14, margin: '0 0 8px 0', color: '#1890ff' }}>膳食调整建议</h4>
          <ul style={{ margin: 0, paddingLeft: 20 }}>
            <li style={{ marginBottom: 4 }}>每日盐摄入量控制在5g以内</li>
            <li style={{ marginBottom: 4 }}>增加新鲜蔬菜摄入（每日不少于500g）</li>
            <li>减少高脂、高糖食物摄入频率</li>
          </ul>
        </div>
        
        <div style={{ marginBottom: 16 }}>
          <h4 style={{ fontSize: 14, margin: '0 0 8px 0', color: '#1890ff' }}>运动建议</h4>
          <ul style={{ margin: 0, paddingLeft: 20 }}>
            <li style={{ marginBottom: 4 }}>每周进行至少150分钟中等强度有氧运动</li>
            <li style={{ marginBottom: 4 }}>推荐快走、慢跑、游泳等运动方式</li>
            <li>避免久坐，每小时起身活动5分钟</li>
          </ul>
        </div>
        
        <div>
          <h4 style={{ fontSize: 14, margin: '0 0 8px 0', color: '#1890ff' }}>定期检查建议</h4>
          <ul style={{ margin: 0, paddingLeft: 20 }}>
            <li style={{ marginBottom: 4 }}>每3个月测量一次血压</li>
            <li style={{ marginBottom: 4 }}>每年进行一次血糖、血脂检测</li>
            <li>定期参加健康知识讲座</li>
          </ul>
        </div>
      </div>
      
      <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button
          type="primary"
          onClick={() => message.success('个性化建议已生成')}
          size="small"
          style={{ padding: '2px 12px' }}
        >
          获取个性化建议
        </Button>
      </Space>
    </div>
  );

  // 渲染其他子选项内容
  const renderOtherContent = (label: string) => (
    <div style={{
      padding: '16px',
      textAlign: 'center',
      backgroundColor: '#f5f7fa',
      borderRadius: 4,
      marginTop: 8
    }}>
      请填写{label}相关信息
    </div>
  );

  // 渲染子选项内容
  const renderChildContent = () => {
    if (!childValue) return null;

    // 患者病情
    if (childValue === 'a1') {
      return (
        <div style={{ marginTop: 12 }}>
          <Table
            columns={diseaseColumns}
            dataSource={diseaseTableData}
            pagination={false}
            scroll={{ x: 'max-content' }}
            size="small"
            style={{ marginBottom: 12 }}
          />
          <Space style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <Button
              onClick={handleDiseaseReset}
              size="small"
              style={{ padding: '2px 12px' }}
            >
              重置
            </Button>
            <Button
              type="primary"
              onClick={handleDiseaseSubmit}
              size="small"
              style={{ padding: '2px 12px' }}
            >
              提交病情
            </Button>
          </Space>
        </div>
      );
    }

    // 膳食摄入
    if (childValue === 'a2') {
      return renderDietContent();
    }

    // 体力活动
    if (childValue === 'a3') {
      return renderActivityContent();
    }

    // 吸烟习惯
    if (childValue === 'a4') {
      return renderSmokingContent();
    }

      if (childValue === 'b1') {
    return (
      <div style={{ marginTop: '16px' }}>
        <h3 style={{ fontSize: 15, margin: '0 0 12px 0', color: '#1890ff' }}>
          常规检查结果
        </h3>
        {/* 渲染体检结果页面，传递当前用户的 bid */}
        <CheckResultPage bid={bid} />
      </div>
    );
  }
    // 风险测评-用户基础信息
    if (childValue === 'c1') {
      return renderUserInfo();
    }

    // 风险测评-健康风险评估
    if (childValue === 'c2') {
      return renderRiskAssessment();
    }

    // 风险测评-干预建议
    if (childValue === 'c3') {
      return renderIntervention();
    }

    // 其他选项
    const currentLabel = childOptions[parentValue as keyof typeof childOptions]
      .find(item => item.value === childValue)?.label;
    return currentLabel ? renderOtherContent(currentLabel) : null;
  };

  // 档案查询相关状态和方法
  const [inputvalue, setinputvalue] = useState('');
  const [name, setname] = useState('');
  const [sex, setsex] = useState('');
  const [age, setage] = useState(0);
  const [bid, setbid] = useState(0);
  const [idy, setid] = useState(0);
const dd={
  id:0,
  pinj:'',
  zt:1
}
  const changeCount1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setinputvalue(event.target.value);
  };

  const fetchUsers = async (value: string) => {
    try {
      const response = await http.getList<Iganyuf>('Order/chay', {});
      console.log("查询结果:", response.data);
      const bb = response.data.filter(u => u.fileNumber === value && u.orderStatus === '正在体检');
      if (bb.length > 0) {
        console.log("匹配结果:", bb[0]);
        setname(bb[0].name);
        setage(bb[0].age);
        setsex(bb[0].sex);
        setbid(bb[0].hid);
       
        
        // 更新风险测评中的用户信息
        setUserInfoItems([
          { key: '1', label: 'UserName', children: bb[0].name },
          { key: '2', label: 'Telephone', children: bb[0].phone || '未填写' },
          { key: '3', label: 'Age', children: bb[0].age },
          { key: '4', label: 'Gender', children: bb[0].sex },
          { key: '5', label: 'File Number', children: bb[0].fileNumber },
          { key: '6', label: 'Examination Status', children: bb[0].orderStatus },
          { key: '7', label: 'Address', span: 2, children: bb[0].address || '未填写' },
          { key: '8', label: 'Remark', children: '无特殊备注' },
        ]);
      } else {
        message.warning('未找到匹配的档案信息');
      }
    } catch (error) {
      console.error("查询失败:", error);
      message.error('查询失败，请稍后重试');
    }
  };
const ganyuf1:Iganyuaddf={
  id: 0,
  fdata: new Date,
  benb: '',
  qinb: '',
  yins: '',
  ypianh: '',
  yxig: '',
  tili: '',
  xiyan: 0,
  pinj: '无',
  zt: 0,
  bid: 0,
  uid:1
}
  const dian = () => {
    if (inputvalue.trim()) {
      fetchUsers(inputvalue);
    } else {
      message.warning('请输入档案号');
    }
  };

  return (
    <div>
      <div 
        style={{ 
          marginBottom: 16, 
          padding: '8px 0' 
        }}
      >
        <span 
          style={{ 
            fontSize: 18, 
            fontWeight: 600, 
            color: '#1890ff', 
            marginRight: 20 
          }}
        >
          健康信息采集
        </span>
        <span 
          style={{ 
            fontSize: 14, 
            color: '#666', 
          }}
        >
          档案号:
        </span>
        <Input 
          onChange={changeCount1} 
          value={inputvalue}  
          size="small" 
          style={{ width: 150, top: '0', margin: '0 8px' }} 
          placeholder="档案号..." 
          prefix={<UserOutlined />} 
        /> 
        <Button 
          icon={<SearchOutlined />} 
          style={{ top: '0', height: 25, marginRight: 20 }}  
          onClick={dian} 
        />
        <span style={{ fontSize: 14, color: '#666', marginRight: 20 }}>姓名:{name}</span>
        <span style={{ fontSize: 14, color: '#666', marginRight: 20 }}>性别:{sex}</span>
        <span style={{ fontSize: 14, color: '#666', marginRight: 20 }}>年龄:{age}</span>
      </div>
      
      <Card
        title=""
        style={{ maxWidth: '90%', margin: '20px auto', overflow: 'auto' }}
        bodyStyle={{ padding: '16px 24px' }}
      >
        {/* 父级选项 */}
        <Radio.Group
          value={parentValue}
          onChange={e => {
            setParentValue(e.target.value);
            setChildValue(''); // 切换父级时重置子集
          }}
          size="small"
          style={{ marginBottom: 8 }}
        >
          <Radio.Button value="a">患者信息</Radio.Button>
          <Radio.Button value="b">体检项目</Radio.Button>
          <Radio.Button value="c">风险测评</Radio.Button>
        </Radio.Group>

        {/* 子集选项 */}
        {childOptions[parentValue as keyof typeof childOptions] && (
          <div>
            <Flex
              align="center"
              style={{
                padding: '8px 12px',
                marginLeft: 4,
                backgroundColor: '#f5f7fa',
                borderRadius: 4
              }}
            >
              <Radio.Group
                value={childValue}
                onChange={e => setChildValue(e.target.value)}
                size="small"
              >
                {childOptions[parentValue as keyof typeof childOptions].map(option => (
                  <Radio.Button key={option.value} value={option.value}>
                    {option.label}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </Flex>

            {/* 子选项内容区域 */}
            {renderChildContent()}
          </div>
        )}
      </Card>
    </div>
  );
};

export default AddUserForm;